package com.fw.application.controller.v2.shop.order;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.annotation.Log;
import com.fw.application.controller.base.BaseController;
import com.fw.common.AliComm;
import com.fw.core.domain.AjaxResult;
import com.fw.enums.BusinessType;
import com.fw.enums.OrderState;
import com.fw.mes.Result;
import com.fw.system.web.model.dto.UserDto;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.v2.OrderApprovalForm;
import com.fw.system.web.model.form.v2.OrderPageQuery;
import com.fw.system.web.model.form.v2.OrderPublishForm;
import com.fw.system.web.model.vo.AddrsVo;
import com.fw.system.web.model.vo.v2.ShopOrderParentVo;
import com.fw.system.web.service.*;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fw.mes.ResultUtils.success;

/**
 * 商户端订单相关API
 */
@Log4j2
@RestController
@RequestMapping("/v2/order")
@Api(tags = "商户端订单相关api")
public class V2OrderController implements BaseController {

    private final IFwOrderService orderService;
    private final IFwParentOrderService parentOrderService;
    private final IFwSpuService spuService;
    private final IFwSkuService skuService;
    private final IFwUserService userService;
    private final IFwAddrsService addrsService;
    private final IFwShopService shopService;
    private final AliComm aliComm;


    public V2OrderController(IFwOrderService orderService,
                             IFwParentOrderService parentOrderService,
                             IFwSpuService spuService,
                             IFwSkuService skuService,
                             IFwUserService userService,
                             IFwAddrsService addrsService,
                             IFwShopService shopService,  AliComm aliComm) {
        this.orderService = orderService;
        this.parentOrderService = parentOrderService;
        this.spuService = spuService;
        this.skuService = skuService;
        this.userService = userService;
        this.addrsService = addrsService;
        this.shopService = shopService;
        this.aliComm = aliComm;
    }

    /**
     *
     *
     * 我的订单列表-全部
     */
    @PostMapping("shopOrderList")
    @ApiOperation("商户订单列表")
    public Result<ShopOrderParentVo> myOrderList(@RequestBody OrderPageQuery orderPageQuery) {
        UserDto shopDto = getShopDto();
        //获取小订单列表对应的，大订单id
        List<Object> parentOrderIdList = orderService.listObjs(Wrappers.<FwOrder>lambdaQuery()
                .select(FwOrder::getParentOrderId)
                .eq(!OrderState.ALL_ORDER.getCode().equals(orderPageQuery.getOrderState()), FwOrder::getStatus, orderPageQuery.getOrderState())
                //全部中排除，申请售后
/*
                .ne(OrderState.ALL_ORDER.getCode().equals(orderPageQuery.getOrderState()), FwOrder::getStatus, OrderState.AFTER_SALE.getCode())
*/
                .eq(orderPageQuery.getAfterSaleState() != 0, FwOrder::getAfterSaleState, orderPageQuery.getAfterSaleState())
                                .eq(FwOrder::getShopId,shopDto.getShopId())
                //剔除删除的订单
                .eq(FwOrder::getRemoveFlag,0)
                //竞猜
//                .eq(isQuiz != -1, FwOrder::getIsQuiz, isQuiz)
                .groupBy(FwOrder::getParentOrderId));

        //防止为空时跳过 in
        if (parentOrderIdList.size() == 0) {
            parentOrderIdList.add("");
        }
        List<FwParentOrder> parentOrderList;
        PageHelper.startPage(orderPageQuery.getPageNum(), orderPageQuery.getPageSize());
        parentOrderList = parentOrderService.list(Wrappers.<FwParentOrder>lambdaQuery()
              //  .eq(FwParentOrder::getUserId, getUser().getId())
//                    .eq(!OrderState.ALL_ORDER.getCode().equals(orderState), FwParentOrder::getState, orderState)
                .in(FwParentOrder::getParentOrderId, parentOrderIdList)
                //                .exists("select 1 from fw_order fo where parent_order_id = fo.parent_order_id ")
                .orderByDesc(FwParentOrder::getCreateTime));
//        }

        //最终的送回List
        List<FwParentOrder> newParentOrderList = new ArrayList<>();

        for (FwParentOrder parentOrder : parentOrderList) {
            //大订单为待支付
            if (OrderState.PENDING_PAYMENT.getCode().equals(parentOrder.getState())) {
                parentOrder.setOrderList(orderService.list(Wrappers.<FwOrder>lambdaQuery()
                        .eq(FwOrder::getParentOrderId, parentOrder.getParentOrderId())));
//                parentOrder.getOrderList().forEach(order -> orderService.perfectOrder(order));
                parentOrder.getOrderList().forEach(orderService::perfectOrder);
                parentOrder.setFwAddr(parentOrder.getOrderList().get(0).getFwAddr());
                parentOrder.setAddrString(parentOrder.getOrderList().get(0).getAddrString());
                newParentOrderList.add(parentOrder);
                continue;
            }
            //大订单非待支付
            List<FwOrder> orderList = orderService.list(Wrappers.<FwOrder>lambdaQuery()
                    .eq(FwOrder::getParentOrderId, parentOrder.getParentOrderId())
                    .orderByDesc(FwOrder::getCreateTime));
            //每个小订单，包装一层大订单
            for (FwOrder order : orderList) {
                order = orderService.perfectOrder(order);
                //填充订单详情
                order.setFwSpu(spuService.getById(order.getSpuId()));
                order.setFwSku(skuService.getById(order.getSkuId()));
                order.setFwAddr(addrsService.getVoById(order.getAddrId()));
                order.setFwShop(shopService.getById(order.getShopId()));
                //填充大订单
                FwParentOrder newParentOrder = new FwParentOrder();
                ArrayList<FwOrder> orderS = new ArrayList<>();
                orderS.add(order);
                newParentOrder.setParentOrderId(order.getId());
                newParentOrder.setParentOrderMoney(order.getTotalPrice());
                newParentOrder.setTotalFullPrice(order.getTotalFullPrice());
                newParentOrder.setShopping(order.getShopping());
                newParentOrder.setFullDiscount(order.getFullDiscount());
                newParentOrder.setOrderList(orderS);
                newParentOrder.setState(order.getStatus());
                newParentOrder.setCreateTime(order.getCreateTime());
                newParentOrder.setFwAddr(order.getFwAddr());
                newParentOrder.setAddrString(order.getAddrString());
                newParentOrderList.add(newParentOrder);
            }
        }
        //订单total
        int orderTotal = parentOrderService.count(Wrappers.<FwParentOrder>lambdaQuery()
                .in(FwParentOrder::getParentOrderId, parentOrderIdList));

        return success(ShopOrderParentVo.builder().total(orderTotal).parentOrders(newParentOrderList).build());
    }

    /**
     * 获取订单详细信息
     */
    @GetMapping(value = "/{id}")
    @ApiOperation("订单详情")
    public Result<FwOrder> getOrderInfo(@PathVariable("id") String id) {
        FwOrder order = orderService.getById(id);
        order.setFwSpu( spuService.getById(order.getSpuId()) );
        order.setFwSku( skuService.getById(order.getSkuId()) );
        //用户信息
        FwUser user = userService.getById(order.getUserId());
        order.setUserName(user.getUserName());
        order.setPhone( user.getPhone() );
        //地址信息
        if (StringUtils.isEmpty(order.getAddrString()) && StringUtils.isNotEmpty(order.getAddrId())) {
            AddrsVo voById = addrsService.getVoById(order.getAddrId());
            if (voById != null) {
                order.setAddrString(voById.getContactName() + "&-fw-&" +
                        voById.getContactPhone() + "&-fw-&" +
                        voById.getProvinceName() +
                        voById.getAreaName() +
                        voById.getCityName() +
                        voById.getAddrInfo());
            }
        }
        if (StringUtils.isNotEmpty(order.getAddrString())) {
            String[] split = order.getAddrString().split("&-fw-&");
            order.setContactName(split[0]);
            order.setContactPhone(split[1]);
            order.setAddrInfo(split[2]);
        }
        return success(order);
    }


    /**
     * @Effect 审批售后订单
     * @Author 姚
     * @Date 2021/7/12
     **/
    @PostMapping("/approvalOrder")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("审批售后订单 订单状态 为 7 的时候 才可以审批售后")
    public Result<Object> approvalOrder(@RequestBody @Validated OrderApprovalForm orderApprovalForm) {
        FwOrder oldOrder = orderService.getById(orderApprovalForm.getId());
        if (!oldOrder.getStatus().equals(OrderState.AFTER_SALE.getCode()) || !Integer.valueOf(1).equals(oldOrder.getAfterSaleState()) ) {
            return new Result<>().fail(1,"该订单无需审批");
        }
        if (OrderState.AFTER_SALE_REJECT.getCode().equals( orderApprovalForm.getAfterSaleState() )
                && StringUtils.isEmpty(orderApprovalForm.getAfterSaleRemark())) {
            return new Result<>().fail(1,"请输入拒绝原因");
        }
        if (orderApprovalForm.getAfterSaleState() == 2) {
            //同意退款
            log.info("退款订单号："+ orderApprovalForm.getId());
            FwOrder order = orderService.getById(orderApprovalForm.getId());
            FwUser user = userService.getById(order.getUserId());
            try {
                aliComm.aliTransfer(user.getAliPhone(), order.getTotalPrice(), user.getAliUserName());
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            orderService.update(Wrappers.<FwOrder>lambdaUpdate()
                    .set(FwOrder::getAfterSaleState, orderApprovalForm.getAfterSaleState())
                    .set(FwOrder::getUpdateTime, LocalDateTime.now())
                    .eq(FwOrder::getId, orderApprovalForm.getId()));
        } else if (orderApprovalForm.getAfterSaleState() == 3) {

            orderService.update(Wrappers.<FwOrder>lambdaUpdate()
                    .set(FwOrder::getAfterSaleState, orderApprovalForm.getAfterSaleState())
                    .set(FwOrder::getAfterSaleRemark, orderApprovalForm.getAfterSaleRemark())
                    .set(FwOrder::getStatus, oldOrder.getStatus())
                    .set(FwOrder::getUpdateTime, LocalDateTime.now())
                    .eq(FwOrder::getId, orderApprovalForm.getId()));
        }

        return success("成功审批售后订单");
    }

    /** 更新快递单号 */
    @PostMapping("/updateCourierNumber")
    @ApiOperation("对订单进行发货！")
    public Result<Object> updateCourierNumber(@Validated @RequestBody OrderPublishForm orderPublishForm){
        FwOrder oldOrder = orderService.getById(orderPublishForm.getId());
        if (!oldOrder.getStatus().equals(OrderState.TO_BE_DELIVERED.getCode())) {
            return new Result<>().fail(1,"非待发货订单不可更新快递信息");
        }
        if (StringUtils.isNotEmpty(oldOrder.getCourierName()) && StringUtils.isNotEmpty(oldOrder.getCourierNumber())) {
            return new Result<>().fail(1,"已存在快递信息");
        }
        if (StringUtils.isEmpty(orderPublishForm.getCourierName()) || StringUtils.isEmpty(orderPublishForm.getCourierNumber())) {
            return new Result<>().fail(1,"运单编号或运单公司名称不可为空");
        }
        //更新快递信息
        orderService.update(Wrappers.<FwOrder>lambdaUpdate()
                .set(FwOrder::getCourierName, orderPublishForm.getCourierName())
                .set(FwOrder::getCourierNumber, orderPublishForm.getCourierNumber())
                .set(FwOrder::getUpdateTime, LocalDateTime.now())
                .set(FwOrder::getStatus, OrderState.TO_BE_RECEIVED.getCode())
                .eq(FwOrder::getId, orderPublishForm.getId()));

        //给商户发钱
        if (oldOrder.getIsQuiz() == 1) {
            FwShop shop = shopService.getById(oldOrder.getShopId());
            if (shop == null) {
                log.error("订单号"+ oldOrder.getId() +"为商户付款时商铺不存在，商铺ID=>"+oldOrder.getShopId());
                return new Result<>().fail(1,"订单号"+ oldOrder.getId() +"为商户付款时商铺不存在，商铺ID=>"+oldOrder.getShopId()) ;
            }
            FwUser user = userService.getById(shop.getUserId());
            if (user == null) {
                log.error("订单号"+ oldOrder.getId() +"为商户付款时商户不存在，商户ID=>"+shop.getUserId());
                return new Result<>().fail(1,"订单号"+ oldOrder.getId() +"为商户付款时商户不存在，商户ID=>"+shop.getUserId()) ;
            }

            //计算给多少钱
/*
            FwSpu spu = spuService.getById(oldOrder.getSpuId());
            BigDecimal shopMoney = spu.getRealPrice().subtract( spu.getPrice() ).multiply( BigDecimal.valueOf(oldOrder.getSpuNumber()) );
*/
            FwSpu spu = spuService.getById(oldOrder.getSpuId());
            FwSku fwSku = skuService.getById(oldOrder.getSkuId());
            BigDecimal shopMoney = fwSku.getSkuMoney().subtract(spu.getPrice()).multiply(BigDecimal.valueOf(oldOrder.getSpuNumber()));

            try {
                aliComm.aliTransfer(user.getAliPhone(), shopMoney, user.getAliUserName());
            } catch (AlipayApiException e) {
                return new Result<>().fail(1,e.getMessage());
            }
        }
        return success("成功更新快递单号");
    }

}
